<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of FileChecker
 *
 * @author Sriram
 */
set_time_limit(0);
ini_set("memory_limit",'128M');
ini_set("max_execution_time",'0');
session_start();
class FileChecker {

    public $data = array();
    
    public function FileChecker($task){
        if($task=='gSet')
            $this->sendSettings();
        else if($task=='sSet'){            
            $this->saveSettings($_POST['settings']);
        }else if($task=='sroot'){
            $this->setProjectRoot(trim($_POST['f']));
        }else if($task=='scan'){
            $this->scanFiles(trim($_POST['f']));
        }else if($task=='dt'){
            if(isset($_SESSION['data']))
                echo $_SESSION['data'];
        }else if($task=='dtclear'){
            unset($_SESSION['data']);            
        }

    }
    
    private function sendSettings(){
        unset($_SESSION['data']);
        if($settings = $this->getSettings()){
            if(trim($settings['projectpath'])==''){
                $settings['projectpath']  = $_SERVER['DOCUMENT_ROOT'];
                $this->writeSettings($settings);
                $settings = $this->getSettings();
            }
            if(strtolower($settings['projectpath'])  == strtolower($_SERVER['DOCUMENT_ROOT']))
                $settings['prgpathnotset']=1;
            echo json_encode($settings);
        }else
            echo '0';
    }
    
    private function getSettings(){
        if(file_exists("../settings.ini")){
            $ini_array = parse_ini_file("../settings.ini");
            return $ini_array;
        }else
            return false;
    }
    
	private function saveSettings($settings){
		if($this->writeSettings($settings))
			$this->sendSettings();
		else
			echo json_encode(array('Error'));
	}
	
    private function writeSettings($settings){        
        if(is_writeable('../settings.ini')) {
            $SFfdescriptor = fopen('../settings.ini', "w" );
            fwrite( $SFfdescriptor, "[Filechecker]\n" );
            foreach($settings as $key => $value){           
                if($key!='serverfilename')
                    $value = trim($value,"/")."/";
                fwrite( $SFfdescriptor, "$key = ".'"'.$value.'"'."\n" );                
                
            }
            fclose( $SFfdescriptor );
            return true;
        } else {
            return false;
        }     
    }
    
	private function setProjectRoot($folder){
		if($this->saveProjectRoot($folder))
                    $this->sendSettings();
		else
                    echo '0';
	
	}
	
	private function saveProjectRoot($folder){
		$settings = $this->getSettings();
		$settings['projectpath'] = $folder;
		if($this->writeSettings($settings))
                    return true;
		else
                    return false;
	}
	
    private function getLocalContent($dir){	
        static $return_result = array();
        $apath = $dir;
        $settings = $this->getSettings(); 
        $dir = str_replace($settings['projectpath'],'',$dir);
               
	if (is_dir($apath)) {	
            if ($dh = opendir($apath)) {
                while (($file = readdir($dh)) !== false) {                    
                    $ftype = filetype($apath . $file);
                    if($file != "." && $file != ".."){
                        if(is_dir($apath . $file)){                            
                            $this->getLocalContent($apath . $file.'/');
                        }else if($ftype != "dir"){        
                            $str = file_get_contents($apath . $file);
                            $str = preg_replace("/[\r\n]+/", " ", $str);
                            $return_result[$dir][$file] = md5($str);
                        }
                    }
                }
                closedir($dh);
            }
	}else{
            $str = file_get_contents($apath);
            $str = preg_replace("/[\r\n]+/", " ", $str);
            $return_result[$dir] = md5($str);
        }
	return $return_result;
    }
    
    function getServerContent($server_execution_path, $folder_path){		
        $folder_path = "folder_path=".$folder_path;
        $ch = curl_init();        
        curl_setopt($ch, CURLOPT_URL, $server_execution_path);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,TRUE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$folder_path);
 	  
        if($curl_rt = curl_exec($ch)){
           $result= trim($curl_rt);
        }else{
           $result=curl_error($ch);
        }
        curl_close($ch);
        
        if($result != ""){            
            return $result;
        } else {
             return array("Error"=>"Error in fetching data.");
        }
    }

    function scanFiles($folder){
        $settings = $this->getSettings();        
        $local_result = $this->getLocalContent(trim($folder));        
        foreach($local_result as $key=>$value){                           
            $server_result = unserialize($this->getServerContent($settings['serverpath'].$settings['serverfilename'],$key));
//            print_r($local_result);
          //  print_r($server_result);exit;
            if(is_array($local_result[$key])){ 
                if(array_diff_assoc($local_result[$key], $server_result[$key]) || array_diff_assoc($server_result[$key],$local_result[$key])){                    
                    $local_files['local'] = array_diff_key($local_result[$key], $server_result[$key]);
                    $server_files['server'] = array_diff_key($server_result[$key], $local_result[$key]);
                    $this->generate_grid($settings['projectpath'].$key,'folder','',true);
                    foreach($local_files['local'] as $fname=>$value){
                        $this->generate_grid($fname,'file','Missing in Server',false);
                        unset($local_result[$key][$fname]);
                    }
                    foreach($server_files['server'] as $fname=>$value){
                        $this->generate_grid($fname,'file','Missing in Local',false);
                    }

                    foreach($local_result[$key] as $fname=>$value){
                        if(isset($server_result[$key][$fname]) && $value == $server_result[$key][$fname]){
                              $this->generate_grid($fname,'file','Identical',false);
                        }else{
                            $this->generate_grid($fname,'file','Varies',false);
                        }
                    }
                }else{
                    $this->generate_grid($settings['projectpath'].$key,'folder','',true);
                    foreach($local_result[$key] as $fname=>$value){
                        $this->generate_grid($fname,'file','Identical',false);
                    }
                }
                
            }else{
//                print_r($server_result);
                if(is_array($server_result[key($local_result)]) && array_key_exists('FileNotExists',$server_result[key($local_result)])){
                    $this->generate_grid(key($local_result),'file','Missing in the Server',true);
                }else if(array_diff_assoc($local_result,$server_result) || array_diff_assoc($server_result,$local_result)){
                    $this->generate_grid($key,'file','Varies',true);
                }else{
                    $this->generate_grid($key,'file','Identical',true);                    
                }
            }
        }        
    }
    
    function generate_grid($name,$type='file',$status='',$root=false){
        if($type=='file')
            $css = 'file ext_txt';
        else
            $css = 'directory expanded';
        if(!isset($_SESSION['data']) && count($this->data) == 0){    
            $index=0;
        }else{
            $this->data = json_decode($_SESSION['data'], true);   
            $index = count($this->data['rows']);
            
        }
        $this->data['rows'][$index]['id']= rand();
        if($root)
            $this->data['rows'][$index]['cell'] = array('<ul class="jqueryFileTree" style="display: block;"><li class="'.$css.'">'.$name."</li></ul>", $type,$status);
        else
            $this->data['rows'][$index]['cell'] = array('<ul class="jqueryFileTree" style="display: block;"><li><ul><li class="'.$css.'" >'.$name.'</li></ul></li></ul>', '<ul><li><ul><li>'.$type.'</li></ul></li></ul>','<ul><li><ul><li>'.$status.'</li></ul></li></ul>');
    	
        $_SESSION['data'] = json_encode($this->data);


        //return $this->data;
    }
}


$obj = new FileChecker(trim($_REQUEST['t']));
?>
